package com.yusheng.controller;

import com.yusheng.dao.QueryStaff;
import com.yusheng.entity.ApprovalRecord;
import com.yusheng.entity.ProcessControl;
import com.yusheng.entity.ProcessControlList;
import com.yusheng.util.JdbcUtil;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;

public class ApprovalAdd extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置缓冲区编码，方便读取中文
        request.setCharacterEncoding("utf-8");
        //response.setContentType("type=text/html;charset=utf-8");之前写成了这样，注意观察细节上有什么不一样
        response.setContentType("text/html;charset=utf-8");
        response.setCharacterEncoding("utf-8");
        //获取request请求体中的参数
        String approvalName=request.getParameter("approvalName");
        String approvalDetail=request.getParameter("approvalDetail");
        String nowTime=request.getParameter("nowtime");
        String stuffNo=request.getParameter("stuffno");
        //根据项目流程名，获取项目流程
        ProcessControlList processControlList=  QueryStaff.queryProcessControl(approvalName);
        //根据参数   创建审批表
        int i=1;
        String mainRecord="main"+(int)(Math.random()*10000);


        try {
            QueryStaff.jdbcUtil=new JdbcUtil();
            QueryStaff.jdbcUtil.getConnection1();
            String s=QueryStaff.jdbcUtil.connection1.toString();
            String s1=QueryStaff.jdbcUtil.toString();
            QueryStaff.jdbcUtil.connection1.setAutoCommit(false);//开始事务
            for (ProcessControl processControl:processControlList.list){

                ApprovalRecord approvalRecord=new ApprovalRecord(null,stuffNo,null,processControl.getApprovalNo(),
                        null,mainRecord,""+i,"0",nowTime,processControl.getProcessName(),
                        approvalDetail,null);
                approvalRecord.setApprovalName("null");
                approvalRecord.setStuffName("null");
                if(QueryStaff.addApprovalRecord(approvalRecord,QueryStaff.jdbcUtil.connection1)){
                    i++;
                }
            }
            QueryStaff.jdbcUtil.connection1.commit();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            QueryStaff.jdbcUtil.close1();
        }


        QueryStaff.setMainCode(mainRecord);
        //设置响应体的编码格式

        PrintWriter out=response.getWriter();
        out.print("<center><h2>增加成功，请前往申请详情页查看审批进度</h2></center>");

    }
}
